package com.example.demo.Controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.demo.Service.UserService;
import com.example.demo.entity.User;
import com.example.demo.utils.RedisUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author yangzai
 */
@RestController
public class UserController {
    private UserService userService;
    private RedisUtils redisUtils;

    private RabbitTemplate rabbitTemplate;
@Autowired
    public void setRabbitTemplate(RabbitTemplate rabbitTemplate) {
        this.rabbitTemplate = rabbitTemplate;
    }

    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }
    @Autowired
    public void setRedisUtils(RedisUtils redisUtils) {
        this.redisUtils = redisUtils;
    }

    @PostMapping("/sdsa")
    public String list(){
        return userService.list(new User())+"";
    }
    @GetMapping("/ceshi")
    public String chaxun(String id) {
        Object o = redisUtils.get(id);
        Object a=!StringUtils.isEmpty(o)? JSONObject.parseObject((String) o,User.class):
                redisUtils.set(id, (JSON.toJSONString(userService.cha(id))));
        rabbitTemplate.convertAndSend("spring.boot.delay.exchange",
                "spring.boot.delay.routingkey",id);
        System.out.println(111);
        System.out.println(222);
        System.out.println(333);
        return a instanceof User?"在缓存中找到啦"+o:"在数据库中找到啦";
    }
    @GetMapping("/zengjia")
    public String zengjia(User user){
        userService.zengjia(user);
        Integer id = user.getId();
        rabbitTemplate.convertAndSend("spring.boot.delay.exchange",
                "spring.boot.delay.routingkey",id+"");
        return id+"";
    }

}
